//
//  CityPickerController.m
//  HZCityPicker
//
//  Created by 黄泽 on 2017/7/13.
//  Copyright © 2017年 黄泽. All rights reserved.
//

#import "CityPickerController.h"
#import "CityPickerSearchResultController.h"
#import "CityGroupCell.h"
#import "CityLocalCell.h"

#import "CityHeaderView.h"
@interface CityPickerController ()
<CityGroupCellDelegate,
SearchResultControllerDelegate,
UISearchBarDelegate,
HZLocationDelegate>

@property (nonatomic, strong) HZLocation *locationManager;

@property (nonatomic, strong) UISearchController *searchController;
@property (nonatomic, strong) CityPickerSearchResultController *searchResultVC;

@property (nonatomic, strong) NSMutableArray *cityData;
@property (nonatomic, strong) NSMutableArray *localCityData;
@property (nonatomic, strong) NSMutableArray *hotCityData;
@property (nonatomic, strong) NSMutableArray *arraySection;

@end

@implementation CityPickerController

//@synthesize data = _data;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.locationManager = [[HZLocation alloc] init];
    [self.locationManager setDelegate:self];
    
    [self.navigationItem setTitle:@"城市选择"];
    UIBarButtonItem *cancelBarButton = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelButtonDown:)];
    
    [self.navigationItem setLeftBarButtonItem:cancelBarButton];
    
    [self.tableView setTableHeaderView:self.searchController.searchBar];
    self.searchController.searchBar.showsCancelButton = YES;
    UIButton *canceLBtn = [self.searchController.searchBar valueForKey:@"cancelButton"];
    [canceLBtn setTitle:@"取消" forState:UIControlStateNormal];
    [canceLBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];

    self.tableView.backgroundColor = UIColorHex(0xffffff);
    self.view.backgroundColor = UIColorHex(0xffffff);
    [self.tableView setSectionIndexBackgroundColor:[UIColor clearColor]];
    [self.tableView setSectionIndexColor:UIColorHex(0x333333)];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
    [self.tableView registerClass:[CityGroupCell class] forCellReuseIdentifier:@"TLCityGroupCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"CityLocalCell" bundle:nil] forCellReuseIdentifier:@"TLCityLocalCell"];
    [self.tableView registerClass:[CityHeaderView class] forHeaderFooterViewReuseIdentifier:@"TLCityHeaderView"];
    
    [self request_cityList];
    [self request_hotCityList];
}

#pragma mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.data.count + 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if (section == 0 || section == 1) {
        return 1;
    } else {
        CityGroup *group = [self.data objectAtIndex:section-2];
        return group.arrayCitys.count;
    }

    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.section) {
        case 0:{
            CityLocalCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TLCityLocalCell"];
            
            [cell fillWithModel:self.localCityData.firstObject];
            
            cell.CityLocalCellBlock = ^{//选中了定位的城市
                
                if (self.localCityData.count > indexPath.row) {
                    
                    CityModel *city = [self.localCityData objectAtIndex:indexPath.row];
                    if (city.cityID.length > 0) {
                        [self didSelctedCity:city];
                    }
                    
                } else {
                    self.locationManager = [[HZLocation alloc] init];
                    [self.locationManager setDelegate:self];
                }
            };
            
            return cell;
        } break;
        case 1:{
            CityGroupCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TLCityGroupCell"];
            [cell setTitle:@"热门城市"];
            [cell setCityArray:self.hotCityData];
            [cell setDelegate:self];
            return cell;
        } break;
        default:{
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
            cell.textLabel.textColor = UIColorHex(0x333333);
            cell.textLabel.font = [UIFont systemFontOfSize:15];
            
            CityGroup *group = [self.data objectAtIndex:indexPath.section-2];
            CityModel *city =  [group.arrayCitys objectAtIndex:indexPath.row];
            [cell.textLabel setText:city.cityName];
            
            return cell;
        } break;
    }
}

#pragma mark UITableViewDelegate
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    switch (section) {
        case 0:{
            return nil;
        } break;
        case 1:{
            return nil;
        } break;
        default:{
            CityHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"TLCityHeaderView"];
            NSString *title = [_arraySection objectAtIndex:section];
            [headerView setTitle:title];
            return headerView;
        } break;
    }
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        return [CityGroupCell getCellHeightOfCityArray:self.hotCityData];
    }
    return 50.0;
}

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0 || section == 1) {
        return CGFLOAT_MIN;
    }
    return 40;
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    switch (indexPath.section) {
        case 0:{
            return;
        } break;
        case 1:{
            return;
        } break;
        default:{
            CityGroup *group = [self.data objectAtIndex:indexPath.section-2];
            CityModel *city = [group.arrayCitys objectAtIndex:indexPath.row];
            [self didSelctedCity:city];
        } break;
    }
}

//索引测title
- (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
    return self.arraySection;
}

- (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    return index;
}

#pragma mark TLCityGroupCellDelegate
- (void) cityGroupCellDidSelectCity:(CityModel *)city {
    [self didSelctedCity:city];
}

#pragma mark TLSearchResultControllerDelegate
- (void) searchResultControllerDidSelectCity:(CityModel *)city
{
    [self.searchController dismissViewControllerAnimated:YES completion:^{
        
    }];
    [self didSelctedCity:city];
}

#pragma mark - Event Response
- (void) cancelButtonDown:(UIBarButtonItem *)sender
{
    if (_delegate && [_delegate respondsToSelector:@selector(cityPickerControllerDidCancel:)]) {
        [_delegate cityPickerControllerDidCancel:self];
    }
}

#pragma mark - Private Methods
- (void) didSelctedCity:(CityModel *)city
{
    if (_delegate && [_delegate respondsToSelector:@selector(cityPickerController:didSelectCity:)]) {
        [_delegate cityPickerController:self didSelectCity:city];
    }
    
    if (self.commonCitys.count >= MAX_COMMON_CITY_NUMBER) {
        [self.commonCitys removeLastObject];
    }
    for (NSString *str in self.commonCitys) {
        if ([city.cityID isEqualToString:str]) {
            [self.commonCitys removeObject:str];
            break;
        }
    }
    [self.commonCitys insertObject:city.cityID atIndex:0];
    [[NSUserDefaults standardUserDefaults] setValue:self.commonCitys forKey:COMMON_CITY_DATA_KEY];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    
    if (self.searchController.searchBar.text.length > 0) {
        self.searchController.searchBar.text = @"";
    } else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}
#pragma mark - Setter
- (void) setCommonCitys:(NSMutableArray *)commonCitys
{
    _commonCitys = commonCitys;
    if (commonCitys != nil && commonCitys.count > 0) {
        [[NSUserDefaults standardUserDefaults] setValue:commonCitys forKey:COMMON_CITY_DATA_KEY];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

#pragma mark - Getter
- (UISearchController *) searchController
{
    if (_searchController == nil) {
        
        _searchController = [[UISearchController alloc] initWithSearchResultsController:self.searchResultVC];
        [_searchController.searchBar setPlaceholder:@"城市名"];
//        _searchController.searchBar.showsCancelButton = YES;
        _searchController.searchBar.delegate = self;
        [_searchController.searchBar setBarTintColor:UIColorHex(0xffffff)];
        [_searchController.searchBar sizeToFit];
        [_searchController setSearchResultsUpdater:self.searchResultVC];

        UIImageView *barImageView = [[[_searchController.searchBar.subviews firstObject] subviews] firstObject];
        barImageView.layer.borderColor = UIColorHex(0xffffff).CGColor;
        barImageView.layer.borderWidth=1;
        


    }
    return _searchController;
}


- (CityPickerSearchResultController *) searchResultVC
{
    if (_searchResultVC == nil) {
        _searchResultVC = [[CityPickerSearchResultController alloc] init];
        _searchResultVC.cityData = self.cityData;
        _searchResultVC.searchResultDelegate = self;
        
    
    }
    return _searchResultVC;
}

- (NSMutableArray *) data
{
    if (_data == nil) {
        _data = [[NSMutableArray alloc] init];
    }
    return _data;
}

//定位成功
- (void)currentLocation:(NSDictionary *)locationDictionary coordinate:(CLLocationCoordinate2D)coordinate {
    NSString *city = [locationDictionary valueForKey:@"City"];
    [self request_cityIdWith:city];
}

/// 拒绝定位
- (void)refuseToUsePositioningSystem:(NSString *)message {

    [SVProgressHUD showWithStatus:@"app未获取到定位权限，如果使用定位功能，请同意定位权限，或者在‘设置’-‘隐私’-‘定位服务’中找到app，并且开启定位权限"];
    [SVProgressHUD dismissWithDelay:2];
}

/// 定位失败
- (void)locateFailure:(NSString *)message {

    [SVProgressHUD showErrorWithStatus:@"定位失败，您还可以手动搜索并选择您所在的城市"];
    [SVProgressHUD dismissWithDelay:2];
}

- (void)locating {
    NSLog(@"定位中");
}

- (void)request_cityIdWith:(NSString *)cityName {
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:cityName forKey:@"cityName"];
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,@"/indexApp/queryCityId"];
    
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        if ([data isKindOfClass:[NSDictionary class]]) {
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {//匹配到城市id
                
                weakSelf.localCityData = @[].mutableCopy;
                
                NSDictionary *resultDic = [data valueForKey:@"data"];
                NSString *cityID = [resultDic valueForKey:@"sellerCityId"];
                
                CityModel *city = [[CityModel alloc] init];
                city.cityID = cityID;
                city.cityName = cityName;
                
                [weakSelf.localCityData addObject:city];
                
                [weakSelf.tableView reloadData];
                
            } else {//未匹配到城市id
                
                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"城市-%@未开通婚前婚后服务，请手动选择一个最近的市为您服务",cityName]];
                [SVProgressHUD dismissWithDelay:2];
            }
        }
    } FailedBlock:^(NSError * _Nonnull error) {
        
    }];
}

- (void)request_cityList {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_CityList];
    
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [[TTNoResultManager shareManager] hideNoResultWithView:weakSelf.view];
        
        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSArray *list = [data valueForKey:@"data"];
                
                if ([list isKindOfClass:[NSArray class]]) {
                    
                    for (NSDictionary *groupDic in list) {
                        CityGroup *group = [[CityGroup alloc] init];
                        group.groupName = [groupDic objectForKey:@"code"];
                        for (NSDictionary *dic in [groupDic objectForKey:@"sysCity"]) {
                            CityModel *city = [[CityModel alloc] init];
                            city.cityID = [dic objectForKey:@"cityId"];
                            city.cityName = [dic objectForKey:@"cityName"];
                            
                            NSString *shortName = [dic objectForKey:@"code"];
                            city.shortName = [Utilities stringToLower:shortName];
                            city.pinyin = [Utilities stringToLower:shortName];
                            city.initials = [dic objectForKey:@"code"];
                            [group.arrayCitys addObject:city];
                            [weakSelf.cityData addObject:city];
                        }
                        [weakSelf.arraySection addObject:group.groupName];
                        [weakSelf.data addObject:group];
                    }
                    
                    if (weakSelf.data.count == 0) {
                        [[TTNoResultManager shareManager] showNoResultWithStateInView:weakSelf.view errorCode:kTTViewState_NoCity btnTitle:@"" didPressButton:^{}];
                    }
                    
                    [weakSelf.tableView reloadData];
                }
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf request_cityList];
        });
    }];
}

- (void)request_hotCityList {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_HotCityList];
    
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [[TTNoResultManager shareManager] hideNoResultWithView:weakSelf.view];
        
        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSArray *list = [data valueForKey:@"data"];
                
                if ([list isKindOfClass:[NSArray class]]) {
                    for (NSDictionary *dic in list) {
                        CityModel *city = [[CityModel alloc] init];
                        city.cityID = [dic objectForKey:@"cityId"];
                        city.cityName = [dic objectForKey:@"cityName"];
                        
                        NSString *shortName = [dic objectForKey:@"code"];
                        city.shortName = [Utilities stringToLower:shortName];
                        city.pinyin = [Utilities stringToLower:shortName];
                        city.initials = [dic objectForKey:@"code"];
                        [weakSelf.hotCityData addObject:city];
                    }
                    [weakSelf.tableView reloadData];
                }
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf request_hotCityList];
        });
    }];
}

- (NSMutableArray *) cityData
{
    if (_cityData == nil) {
        _cityData = [[NSMutableArray alloc] init];
    }
    return _cityData;
}

- (NSMutableArray *) localCityData
{
    if (_localCityData == nil) {
        _localCityData = [[NSMutableArray alloc] init];
        if (self.locationCityName != nil) {
            CityModel *city = nil;
            for (CityModel *item in self.cityData) {
                if ([item.cityName isEqualToString:self.locationCityName]) {
                    city = item;
                    break;
                }
            }
            if (city == nil) {
                NSLog(@"Not Found City: %@", self.locationCityName);
            }
            else {
                [_localCityData addObject:city];
            }
        }
    }
    return _localCityData;
}

//热门城市
- (NSMutableArray *) hotCityData
{
    if (_hotCityData == nil) {
        _hotCityData = [[NSMutableArray alloc] init];
    }
    return _hotCityData;
}

- (NSMutableArray *) arraySection
{
    if (_arraySection == nil) {
        _arraySection = [[NSMutableArray alloc] initWithObjects:@"定位:",@"热门", nil];
    }
    return _arraySection;
}

@end
